package dongze.com.ckdj.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import dongze.com.ckdj.R;
import dongze.com.ckdj.util.Util;

public class ImageCaptureActivity extends ProgressableActivity {
    ResultReceiver receiver;
    RecyclerView recyclerView;
    TextView textView;
    private static final int PHOTO_INTENT = 1234;
    private static final String IMAGE_PRIFIX = "captured";
    private static final int MAX_COUNT = 20;
    private File imageFile;
    private List<String> imgs = new ArrayList<>(20);
    private ImageAdapter adapter = new ImageAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getExtras() != null) {
            receiver = (ResultReceiver) getIntent().getExtras().get("result_receiver");
            if (receiver == null)
                finish();

            List<String> list = getIntent().getExtras().getStringArrayList("imgs");
            if (list != null)
                imgs.addAll(list);
        }

        setContentView(R.layout.activity_image_caputre);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setAdapter(adapter);
        textView = (TextView) findViewById(R.id.text);
        updateImageCount(imgs.size());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.image_capture, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.capture) {
            if (imgs.size() >= MAX_COUNT) {
                new AlertDialog.Builder(this)
                        .setMessage("照片数量已经达到20张")
                        .create()
                        .show();
                return true;
            }

            if (!Util.checkCapturePermission(this))
                return true;

            if (imageFile != null && imageFile.exists())
                Util.deleteFile(imageFile.getAbsolutePath());

            imageFile = Util.getImageFile(IMAGE_PRIFIX);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentapiVersion < 24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
                startActivityForResult(intent, PHOTO_INTENT);
            } else {
                Uri uri = FileProvider.getUriForFile(this, "dongze.com.ckdj.fileprovider", imageFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivityForResult(intent, PHOTO_INTENT);
            }
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_INTENT && resultCode == Activity.RESULT_OK && imageFile != null && imageFile.exists()) {
            imgs.add(imageFile.getAbsolutePath());
            imageFile = null;
            adapter.notifyDataSetChanged();
            updateImageCount(imgs.size());
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void finish() {
        Bundle bundle = new Bundle();
        ArrayList<String> imgs = new ArrayList<>();
        imgs.addAll(this.imgs);
        bundle.putStringArrayList("imgs", imgs);
        receiver.send(Activity.RESULT_OK, bundle);
        super.finish();
    }

    private void updateImageCount(int count) {
        if (count == 0)
            textView.setText("没有拍照片");
        else
            textView.setText("已拍摄" + count + "张照片，还可拍摄" + (MAX_COUNT - count) + "张照片");
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;

        public ViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.img);
        }
    }

    class ImageAdapter extends RecyclerView.Adapter<ViewHolder> {

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_capture_list_item, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Glide.with(holder.imageView.getContext()).load(imgs.get(position)).into(holder.imageView);
        }

        @Override
        public int getItemCount() {
            return imgs.size();
        }
    }
}
